// 配置路由
import Vue from "vue";
import VueRouter from "vue-router";

// 引入路由
import routes from "./routers";

// 引入store
import store from "@/store";

//使用插件
Vue.use(VueRouter);

// 先把VueRouter原型对象的push先保存一份
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

//重写push|replace
// 1.第一个参数:告诉原来的push方法,往哪里跳转
VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    originPush.call(this, location, resolve, reject);
  } else {
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject);
  } else {
    originReplace.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

//配置路由
let router = new VueRouter({
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 返回的y等于0代表滚动条在最上方
    return { y: 0 };
  },
});

// 全局守卫(在路由器跳转之间进行判断)
// to:(跳转的路由信息) from:(获取到从哪来的路由信息) next:(放行的函数) next(path:放行到指定函数)
router.beforeEach(async (to, from, next) => {
  // 用户信息
  let name = store.state.user.userInfo.name;
  // 用户登录了才会有token
  let token = store.state.user.token;
  // 用户已经登录
  if (token) {
    // 用户已经登陆过还想去login
    if (to.path == "/login") {
      token = "";
      next("/login");
    } else {
      // 如果有name那么进行跳转
      if (name) {
        next();
      } else {
        try {
          // 如果没有用户信息,就调用action进行派发,获取用户信息,在进行跳转
          await store.dispatch("getUserInfo");
          next();
        } catch (error) {
          // token失效
          // 清除token
          await store.dispatch("userLoginout");
          next();
        }
      }
    }
  } else {
    // 未登录 不能去支付,交易,个人中心,相关的页面
    // 未登录 只能去login,home,search,Register
    let toPath = to.path;
    if (
      toPath.indexOf("/trade") != -1 ||
      toPath.indexOf("/pay") != -1 ||
      toPath.indexOf("/center") != -1 ||
      toPath.indexOf("/shop") != -1 ||
      toPath.indexOf("/addcart") != -1
    ) {
      alert('请先完成登录')
      next("/login");
    } else {
      // 去去login,home,search,Register放行
      next();
    }
  }
});

export default router;
